package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.xuanzheng.company.entity.AttendanceRecord;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AttendanceRecordService;
import com.xuanzheng.company.service.CompanyEmployeeService;
import com.xuanzheng.company.service.impl.AttendanceRecordServiceImpl;
import com.xuanzheng.company.service.impl.CompanyEmployeeServiceImpl;
import com.xuanzheng.company.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/attendance/records")
public class GetAttendanceRecordsServlet extends HttpServlet {
    private AttendanceRecordService attendanceRecordService = new AttendanceRecordServiceImpl();
    private CompanyEmployeeService companyEmployeeService = new CompanyEmployeeServiceImpl();
    private Gson gson;
    
    // 初始化Gson，添加Timestamp序列化器
    public GetAttendanceRecordsServlet() {
        // 创建一个自定义的Timestamp序列化器
        JsonSerializer<Timestamp> timestampSerializer = new JsonSerializer<Timestamp>() {
            @Override
            public JsonElement serialize(Timestamp timestamp, Type typeOfSrc, JsonSerializationContext context) {
                // 使用SimpleDateFormat格式化时间戳
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return new JsonPrimitive(dateFormat.format(timestamp));
            }
        };
        
        // 使用GsonBuilder注册序列化器
        this.gson = new GsonBuilder()
                .registerTypeAdapter(Timestamp.class, timestampSerializer)
                .create();
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 获取当前登录用户
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        String type = req.getParameter("type"); // 请求类型：user-用户打卡记录，company-公司打卡记录
        
        if ("user".equals(type)) {
            // 获取日期参数（可选）
            String dateStr = req.getParameter("date");
            
            // 使用直接SQL查询获取用户打卡记录
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            List<Map<String, Object>> records = new ArrayList<>();
            
            try {
                conn = DBUtil.getConnection();
                String sql;
                
                // 使用最简单的查询
                sql = "SELECT * FROM attendance_record WHERE user_id = ?";
                
                // System.out.println("执行SQL查询: " + sql);
                // System.out.println("参数 - 用户ID: " + user.getId());
                
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, user.getId());
                
                rs = pstmt.executeQuery();
                
                while (rs.next()) {
                    Map<String, Object> record = new HashMap<>();
                    try {
                        record.put("id", rs.getString("id"));
                        record.put("userId", rs.getString("user_id"));
                        record.put("companyId", rs.getString("company_id"));
                        record.put("employeeNumber", rs.getString("employee_number"));
                        record.put("checkInTime", rs.getTimestamp("check_in_time") != null ? rs.getTimestamp("check_in_time").toString() : null);
                        record.put("checkOutTime", rs.getTimestamp("check_out_time") != null ? rs.getTimestamp("check_out_time").toString() : null);
                        record.put("attendanceDate", rs.getDate("attendance_date").toString());
                        record.put("recordDate", rs.getDate("attendance_date").toString());
                        
                        record.put("isLate", false);
                        record.put("isEarlyLeave", false);
                        
                        // System.out.println("查询到打卡记录: ID=" + record.get("id") + 
                        //     ", 用户ID=" + record.get("userId") + 
                        //     ", 员工编号=" + record.get("employeeNumber") + 
                        //     ", 上班时间=" + record.get("checkInTime") + 
                        //     ", 下班时间=" + record.get("checkOutTime"));
                        
                        // 如果有日期过滤，只添加匹配的记录
                        if (dateStr != null && !dateStr.isEmpty()) {
                            String recordDate = record.get("attendanceDate").toString();
                            if (recordDate.contains(dateStr) || dateStr.contains(recordDate)) {
                                records.add(record);
                            }
                        } else {
                            records.add(record);
                        }
                    } catch (Exception e) {
                        System.err.println("处理记录时出错: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
                
                // System.out.println("查询结果: 共" + records.size() + "条记录");
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("data", records);
                
                String jsonResult = gson.toJson(result);
                // System.out.println("用户打卡记录JSON: " + jsonResult);
                out.print(jsonResult);
                
            } catch (SQLException e) {
                System.err.println("查询打卡记录出错: " + e.getMessage());
                e.printStackTrace();
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "获取打卡记录失败，系统错误: " + e.getMessage());
                out.print(gson.toJson(result));
            } finally {
                DBUtil.close(conn, pstmt, rs);
            }
        } else if ("company".equals(type)) {
            // 检查是否是公司负责人
            if (user.getRole() != 1) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "只有公司负责人可以查看公司打卡记录");
                out.print(gson.toJson(result));
                return;
            }
            
            // 获取公司ID
            String companyId = req.getParameter("companyId");
            if (companyId == null || companyId.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "公司ID不能为空");
                out.print(gson.toJson(result));
                return;
            }
            
            // 获取日期参数（可选）
            String dateStr = req.getParameter("date");
            
            // 如果没有提供日期参数，默认使用当天日期
            if (dateStr == null || dateStr.isEmpty()) {
                // 获取当前日期并格式化为YYYY-MM-DD
                java.time.LocalDate today = java.time.LocalDate.now();
                dateStr = today.toString();
                // System.out.println("未提供日期参数，使用当前日期: " + dateStr);
            }
            
            // 使用直接SQL查询获取打卡记录
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            List<Map<String, Object>> records = new ArrayList<>();
            
            try {
                conn = DBUtil.getConnection();
                String sql;
                
                // 使用带有日期过滤的查询
                sql = "SELECT * FROM attendance_record WHERE company_id = ? AND attendance_date = ?";
                
                // System.out.println("执行SQL查询: " + sql);
                // System.out.println("参数 - 公司ID: " + companyId + ", 日期: " + dateStr);
                
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, companyId);
                pstmt.setString(2, dateStr);
                
                rs = pstmt.executeQuery();
                
                while (rs.next()) {
                    Map<String, Object> record = new HashMap<>();
                    try {
                        record.put("id", rs.getString("id"));
                        record.put("userId", rs.getString("user_id"));
                        record.put("companyId", rs.getString("company_id"));
                        record.put("employeeNumber", rs.getString("employee_number"));
                        record.put("checkInTime", rs.getTimestamp("check_in_time") != null ? rs.getTimestamp("check_in_time").toString() : null);
                        record.put("checkOutTime", rs.getTimestamp("check_out_time") != null ? rs.getTimestamp("check_out_time").toString() : null);
                        record.put("attendanceDate", rs.getDate("attendance_date").toString());
                        record.put("recordDate", rs.getDate("attendance_date").toString());
                        
                        // 添加用户名（从用户ID获取）
                        String userId = rs.getString("user_id");
                        PreparedStatement userStmt = null;
                        ResultSet userRs = null;
                        try {
                            userStmt = conn.prepareStatement("SELECT name FROM user WHERE id = ?");
                            userStmt.setString(1, userId);
                            userRs = userStmt.executeQuery();
                            if (userRs.next()) {
                                record.put("userName", userRs.getString("name"));
                                record.put("employeeName", userRs.getString("name"));
                            } else {
                                record.put("userName", "未知用户");
                                record.put("employeeName", "未知用户");
                            }
                        } finally {
                            if (userRs != null) userRs.close();
                            if (userStmt != null) userStmt.close();
                        }
                        
                        record.put("isLate", false);
                        record.put("isEarlyLeave", false);
                        
                        // System.out.println("查询到打卡记录: ID=" + record.get("id") + 
                        //     ", 用户ID=" + record.get("userId") + 
                        //     ", 员工编号=" + record.get("employeeNumber") + 
                        //     ", 上班时间=" + record.get("checkInTime") + 
                        //     ", 下班时间=" + record.get("checkOutTime"));
                        
                        // 如果有日期过滤，只添加匹配的记录
                        if (dateStr != null && !dateStr.isEmpty()) {
                            String recordDate = record.get("attendanceDate").toString();
                            if (recordDate.contains(dateStr) || dateStr.contains(recordDate)) {
                                records.add(record);
                            }
                        } else {
                            records.add(record);
                        }
                    } catch (Exception e) {
                        System.err.println("处理记录时出错: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
                
                // System.out.println("查询结果: 共" + records.size() + "条记录");
                
                // 获取公司员工总数
                int totalEmployees = companyEmployeeService.countEmployeesByCompanyId(companyId);
                // 需要打卡的员工数量（不包括负责人）
                int attendanceEmployees = totalEmployees > 0 ? totalEmployees - 1 : 0;
                
                // System.out.println("公司员工总数: " + totalEmployees);
                // System.out.println("需要打卡的员工数量(不包括负责人): " + attendanceEmployees);
                
                // 创建打卡统计对象
                Map<String, Object> todayCount = new HashMap<>();
                todayCount.put("totalEmployees", attendanceEmployees);
                
                // 统计打卡人数
                int checkedInCount = 0;
                int checkedOutCount = 0;
                
                for (Map<String, Object> record : records) {
                    if (record.get("checkInTime") != null) {
                        checkedInCount++;
                    }
                    if (record.get("checkOutTime") != null) {
                        checkedOutCount++;
                    }
                }
                
                // 如果有记录但统计为0，手动设置为记录数量
                if (records.size() > 0 && checkedInCount == 0 && checkedOutCount == 0) {
                    checkedInCount = records.size();
                    checkedOutCount = records.size();
                }
                
                todayCount.put("checkedInCount", checkedInCount);
                todayCount.put("checkedOutCount", checkedOutCount);
                todayCount.put("lateCount", 0);
                todayCount.put("earlyLeaveCount", 0);
                
                // 返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("data", records);
                result.put("todayCount", todayCount);
                
                String jsonResult = gson.toJson(result);
                // System.out.println("返回JSON长度: " + jsonResult.length() + "字节");
                out.print(jsonResult);
                
            } catch (SQLException e) {
                System.err.println("查询打卡记录出错: " + e.getMessage());
                e.printStackTrace();
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "获取打卡记录失败，系统错误: " + e.getMessage());
                out.print(gson.toJson(result));
            } finally {
                DBUtil.close(conn, pstmt, rs);
            }
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "请求类型错误");
            out.print(gson.toJson(result));
        }
    }
} 